package com.chuangshu.chuangshuteam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chuangshu.chuangshuteam.config.BaseContext;
import com.chuangshu.chuangshuteam.dto.ApplicationDto;
import com.chuangshu.chuangshuteam.dto.FileMetadataDto;
import com.chuangshu.chuangshuteam.dto.Result;
import com.chuangshu.chuangshuteam.entity.Applications;
import com.chuangshu.chuangshuteam.entity.BusinessKey;
import com.chuangshu.chuangshuteam.entity.FileInfo;
import com.chuangshu.chuangshuteam.mapper.ApplicationsMapper;
import com.chuangshu.chuangshuteam.mapper.FileInfoMapper;
import com.chuangshu.chuangshuteam.service.ApplicationsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuangshu.chuangshuteam.vo.ApplicationVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author k
 * @since 2025-09-21
 */
@Service
public class ApplicationsServiceImpl extends ServiceImpl<ApplicationsMapper, Applications> implements ApplicationsService {
    @Autowired
    private ApplicationsMapper applicationsMapper;

    @Autowired
    private FileInfoMapper fileInfoMapper;

    @Override
    @Transactional
    public Result submitApplication(ApplicationVo applicationVo) {
        // 参数校验
//        if (applicationVo.getUserId() == null || applicationVo.getUserId() <= 0) {
//            return Result.fail("请提供有效的用户ID");
//        }
        if (applicationVo.getRecruitmentCycleId() == null || applicationVo.getRecruitmentCycleId() <= 0) {
            return Result.fail("请提供有效的招聘周期ID");
        }
        if (applicationVo.getApplicantName() == null || applicationVo.getApplicantName().isEmpty()) {
            return Result.fail("请填写申请人姓名");
        }
        if (applicationVo.getDirection() == null || applicationVo.getDirection().isEmpty()) {
            return Result.fail("请填写申请方向");
        }

        applicationVo.setUserId(BaseContext.getCurrentId());
        // 检查是否已存在相同用户在同一招聘周期的申请
        QueryWrapper<Applications> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", applicationVo.getUserId())
                .eq("recruitment_cycle_id", applicationVo.getRecruitmentCycleId());
        if (this.count(queryWrapper) > 10) {
            return Result.fail("您提交的申请过多暂时无法提交");
        }

        // 创建申请记录
        Applications application = new Applications();
        BeanUtils.copyProperties(applicationVo, application);


        // 设置默认状态
        application.setRound1Status("pending");
        application.setRound2Status("pending");
        application.setFinalStatus("pending");

        // 保存申请记录
        this.save(application);

        // 处理文件上传（如果有）
        if (applicationVo.getFileMetadataDtos() != null && !applicationVo.getFileMetadataDtos().isEmpty()) {
            Long applicationId = application.getId();
            List<FileMetadataDto> fileMetadataDtos = applicationVo.getFileMetadataDtos();

            for (FileMetadataDto fileMetadataDto : fileMetadataDtos) {
                FileInfo fileInfo = new FileInfo();
                BeanUtils.copyProperties(fileMetadataDto, fileInfo);
                fileInfo.setCreatedBy(BaseContext.getCurrentId());
                fileInfo.setBusinessId(applicationId);
                fileInfo.setBusinessType(BusinessKey.APPLICATIONS_ID);
                fileInfoMapper.insert(fileInfo);
            }
        }

        return Result.ok("申请提交成功");
    }
    @Override
    public Result getByPage(Integer page, Integer pageSize, String direction) {
        // 创建分页对象
        Page<Applications> applicationsPage = new Page<>(page, pageSize);

        // 构建查询条件，按创建时间降序排序
        QueryWrapper<Applications> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("created_at");
        if (direction != null && !direction.isEmpty()){
            queryWrapper.eq("direction", direction);
        }

        // 执行分页查询
        Page<Applications> pageResult = this.page(applicationsPage, queryWrapper);

        // 转换为 DTO 对象
        Page<ApplicationDto> dtoPage = new Page<>(page, pageSize);
        dtoPage.setTotal(pageResult.getTotal());
        dtoPage.setPages(pageResult.getPages());

        List<ApplicationDto> dtoList = new ArrayList<>();
        for (Applications application : pageResult.getRecords()) {
            ApplicationDto dto = new ApplicationDto();
            BeanUtils.copyProperties(application, dto);
            dtoList.add(dto);
        }
        dtoPage.setRecords(dtoList);

        return Result.ok(dtoPage);
    }

    @Override
    public List<ApplicationDto> getApplicationsByRecruitmentCycleId(Long recruitmentCycleId) {
        // 创建查询条件
        LambdaQueryWrapper<Applications> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Applications::getRecruitmentCycleId, recruitmentCycleId);

        // 查询数据
        List<Applications> applicationsList = this.list(queryWrapper);

        // 转换为 DTO 对象
        List<ApplicationDto> dtoList = new ArrayList<>();
        for (Applications application : applicationsList) {
            ApplicationDto dto = new ApplicationDto();
            BeanUtils.copyProperties(application, dto);
            dtoList.add(dto);
        }

        return dtoList;
    }
    @Override
    public ApplicationDto getApplicationDetailById(Long id) {
        // 查询申请详情
        Applications application = this.getById(id);
        if (application == null) {
            return null;
        }

        // 转换为 DTO 对象
        ApplicationDto dto = new ApplicationDto();
        BeanUtils.copyProperties(application, dto);

        // 查询关联的文件
        LambdaQueryWrapper<FileInfo> fileQueryWrapper = new LambdaQueryWrapper<>();
        fileQueryWrapper.eq(FileInfo::getBusinessId, id)
                .eq(FileInfo::getBusinessType, BusinessKey.APPLICATIONS_ID);
        List<FileInfo> fileList = fileInfoMapper.selectList(fileQueryWrapper);

        ArrayList<FileMetadataDto> fileMetadataDtos = new ArrayList<>();
        for (FileInfo file : fileList) {
            FileMetadataDto fileMetadataDto = new FileMetadataDto();
            BeanUtils.copyProperties(file, fileMetadataDto);
            fileMetadataDtos.add(fileMetadataDto);
        }

        dto.setFileMetadataDtos(fileMetadataDtos);

        return dto;
    }

    @Override
    public Result updateApplication(ApplicationVo applicationVo) {
        // 参数校验
        if (applicationVo.getId() == null || applicationVo.getId() <= 0) {
            return Result.fail("请提供有效的申请ID");
        }
//        if (applicationVo.getUserId() == null || applicationVo.getUserId() <= 0) {
//            return Result.fail("请提供有效的用户ID");
//        }
        applicationVo.setUserId(BaseContext.getCurrentId());
        if (applicationVo.getRecruitmentCycleId() == null || applicationVo.getRecruitmentCycleId() <= 0) {
            return Result.fail("请提供有效的招聘周期ID");
        }
        if (applicationVo.getApplicantName() == null || applicationVo.getApplicantName().isEmpty()) {
            return Result.fail("请填写申请人姓名");
        }
        if (applicationVo.getDirection() == null || applicationVo.getDirection().isEmpty()) {
            return Result.fail("请填写申请方向");
        }

        // 检查申请是否存在
        Applications existingApplication = this.getById(applicationVo.getId());
        if (existingApplication == null) {
            return Result.fail("申请不存在");
        }

        // 更新申请信息
        BeanUtils.copyProperties(applicationVo, existingApplication);
        existingApplication.setUpdatedAt(LocalDateTime.now());
        this.updateById(existingApplication);

        return Result.ok("更新成功");
    }

    @Override
    @Transactional
    public Result deleteApplication(Long id) {
        // 参数校验
        if (id == null || id <= 0) {
            return Result.fail("请提供有效的申请ID");
        }

        // 检查申请是否存在
        Applications existingApplication = this.getById(id);
        if (existingApplication == null) {
            return Result.fail("申请不存在");
        }

        // 删除关联的文件
        QueryWrapper<FileInfo> fileQueryWrapper = new QueryWrapper<>();
        fileQueryWrapper.eq("business_id", id);
        fileQueryWrapper.eq("business_type", BusinessKey.APPLICATIONS_ID);
        fileInfoMapper.delete(fileQueryWrapper);

        // 删除申请
        this.removeById(id);

        return Result.ok("删除成功");
    }

    @Override
    public Result getSelfApplications() {
        LambdaQueryWrapper<Applications> applicationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        applicationsLambdaQueryWrapper.eq(Applications::getUserId, BaseContext.getCurrentId());
        List<Applications> applications = this.list(applicationsLambdaQueryWrapper);
        return Result.ok(applications);
    }

    @Override
    @Transactional
    public Result deleteSelfApplication(Long id) {
        // 参数校验
        if (id == null || id <= 0) {
            return Result.fail("请提供有效的申请ID");
        }

        // 检查申请是否存在
        Applications existingApplication = this.getById(id);
        if (existingApplication == null) {
            return Result.fail("申请不存在");
        }

        // 检查是否是当前用户自己的申请
        if (!existingApplication.getUserId().equals(BaseContext.getCurrentId())) {
            return Result.fail("无权限删除他人的申请");
        }

        // 删除关联的文件
        QueryWrapper<FileInfo> fileQueryWrapper = new QueryWrapper<>();
        fileQueryWrapper.eq("business_id", id);
        fileQueryWrapper.eq("business_type", BusinessKey.APPLICATIONS_ID);
        fileInfoMapper.delete(fileQueryWrapper);

        // 删除申请
        this.removeById(id);

        return Result.ok("删除成功");
    }
}
